use chrono::Utc;
use sqlx::SqlitePool;
use crate::error::AppResult;
use crate::models::{Chat, CreateChat};

/// 创建聊天记录
pub async fn create(pool: &SqlitePool, create_chat: &CreateChat) -> AppResult<Chat> {
    let now = Utc::now();
    
    let result = sqlx::query(
        "INSERT INTO chat (user_id, user_message, ai_message, created_at, updated_at) VALUES (?, ?, ?, ?, ?)"
    )
    .bind(create_chat.user_id)
    .bind(&create_chat.user_message)
    .bind(&create_chat.ai_message)
    .bind(now)
    .bind(now)
    .execute(pool)
    .await?;
    
    let chat_id = result.last_insert_rowid();
    
    let chat = find_by_id(pool, chat_id).await?
        .expect("Failed to find newly created chat");
    
    Ok(chat)
}

/// 根据 ID 查找聊天记录
pub async fn find_by_id(pool: &SqlitePool, id: i64) -> AppResult<Option<Chat>> {
    let chat = sqlx::query_as::<_, Chat>(
        "SELECT * FROM chat WHERE id = ?"
    )
    .bind(id)
    .fetch_optional(pool)
    .await?;
    
    Ok(chat)
}

/// 查找用户的聊天记录
pub async fn find_by_user_id(pool: &SqlitePool, user_id: i64, limit: i64) -> AppResult<Vec<Chat>> {
    let chats = sqlx::query_as::<_, Chat>(
        "SELECT * FROM chat WHERE user_id = ? ORDER BY created_at DESC LIMIT ?"
    )
    .bind(user_id)
    .bind(limit)
    .fetch_all(pool)
    .await?;
    
    Ok(chats)
}
